/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * Input Stream wrapper that reads a fixed amount of bytes from another input
 * stream. Useful e.g. to avoid reading beyond the HTTP content length.
 * 
 * @author kentelt
 * 
 */
public class BoundInputStream extends InputStream {

	InputStream is;
	int remaining;

	public BoundInputStream(InputStream is, int length) {
		this.is = is;
		this.remaining = length;
	}

	public int available() throws IOException {
		int avail = is.available();
		return avail < remaining ? avail : remaining;
	}

	public void close() {
		try {
			is.close();
		} catch (IOException ignored) {
		}
	}

	public int read() throws IOException {

		if (remaining <= 0)
			return -1;
		remaining--;
		return is.read();
	}

	public int read(byte[] data, int start, int max) throws IOException {
		if (max > remaining)
			max = remaining;

		int actual = is.read(data, start, max);

		if (actual > 0)
			remaining -= actual;

		return actual;
	}
}
